package com.jinjia.ordersys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jinjia.ordersys.domain.Person;
import com.jinjia.ordersys.service.AuthService;
import com.jinjia.ordersys.service.PersonService;
import com.jinjia.ordersys.util.*;
import com.jinjia.ordersys.vo.UserLoginVo;

import java.util.*;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: fhz
 * @Date: 11:15 2018-12-17
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private PersonService personService;

    @Override
    public UserLoginVo getUserLoginVo(String code) {
        UserLoginVo userLoginVo = new UserLoginVo();

        Map<String, Object> paramMap = new HashMap<>(4);
        paramMap.put("appid", ConstantUtil.APP_ID);
        paramMap.put("secret", ConstantUtil.APP_SECRET);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", ConstantUtil.AUTH_ORIZATION_CODE);

        String result = null;
        try {
            result = HttpRequestUtil.httpGet(ConstantUtil.WEIXIN_LOGIN, paramMap);
            log.info("response data info:   {}", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!jsonObject.containsKey("errcode")) {
            String openId = (String) jsonObject.get("openid");
            if (openId != null && !"".equals(openId)) {
                Person person = personService.getPersonInfoByOpenid(openId);
                if (person != null) {
                    BeanUtils.copyProperties(person, userLoginVo);
                } else {
                    log.info("该账号未绑定");
                    userLoginVo.setOpenId(openId);
                }
            } else {
                userLoginVo.setOpenId(openId);
            }
            String wxSessionKey = (String) jsonObject.get("session_key");
            userLoginVo.setWxSessionKey(wxSessionKey);
        } else {
            log.info("微信登录回调异常");
        }
        return userLoginVo;
    }

}
